(function () {
  var AutoReader = function (opt) {
    this.oPlayBtn = opt.playBtn;
    this.oTopBtn = opt.topBtn;
    this.oHeader = opt.header;
    this.init = init;
  };

  var playing = false,
    t = null;

  AutoReader.prototype.handleTopBtnClick = function (e) {
    window.scrollTo(0, 0);
  };

  AutoReader.prototype.handleWindowScroll = function () {
    var sTop = getScrollOffset().top;
    //滚动页面 sTop数值(0 - xxxx)
    this.oTopBtn.style.display = sTop ? 'block' : 'none';
  };

  AutoReader.prototype.handlePlayBtnClick = function (e) {
    var sTop = getScrollOffset().top,
      viewPortHeight = getViewportSize().height,
      pageHeight = getScrollSize().height,
      oPlay = this.oPlayBtn.getElementsByClassName('play')[0],
      oPause = this.oPlayBtn.getElementsByClassName('stop')[0];

    /**
     * 假如页面宽高的数值比可视窗口还大时，会显示滚动条，
     * 实际上溢出看不见的部分也是页面的内容。
     * 可以理解为滚动条滚动距离加上可视窗口大小就等于页面(或一个大盒子)的宽高。
     */

    // console.log(sTop, viewPortHeight, pageHeight);
    //6479 723 7158

    //已经是触底的情况时，用户点击自动播放按钮是无效的
    if (sTop + viewPortHeight >= pageHeight) {
      // console.log('触底了');
      return; //停止自动播放
    }

    //非自动滚动时说明用户正在点击自动播放按钮
    if (!playing) {
      t = setInterval(function () {
        //每隔10毫秒要获取新的滚动距离
        var sTop = getScrollOffset().top;
        //触底时需要清除计时器从而暂停自动播放
        if (sTop + viewPortHeight >= pageHeight) {
          clearInterval(t);
          switchBtn('play', oPlay, oPause);
          playing = false;
        } else {
          //没有触底时则一直在自动播放
          //每10毫秒进行纵向下移动
          window.scrollBy(0, 1);
          switchBtn('pause', oPlay, oPause);
        }
      }, 10);
      playing = true;
    } else {
      //正在滚动时 用户有可能点击暂停
      switchBtn('play', oPlay, oPause);
      playing = false;
      clearInterval(t);
    }
  };

  function switchBtn(type, oPlay, oPause) {
    switch (type) {
      case 'play':
        oPlay.style.display = 'block';
        oPause.style.display = 'none';
        break;
      case 'pause':
        oPlay.style.display = 'none';
        oPause.style.display = 'block';
        break;
      default:
        break;
    }
  }

  function bindEvent() {
    addEvent(window, 'scroll', this.handleWindowScroll.bind(this), false);
    addEvent(this.oTopBtn, 'click', this.handleTopBtnClick.bind(this), false);
    addEvent(this.oHeader, 'click', this.handleTopBtnClick.bind(this), false);
    addEvent(this.oPlayBtn, 'click', this.handlePlayBtnClick.bind(this), false);
  }

  function init() {
    bindEvent.call(this);
  }

  window.AutoReader = AutoReader;
})();
